import { reactive } from "vue"
import { pinyin } from 'pinyin-pro';
import { getBasis, createTopic, saveTopic } from "@/api"
// utils
import { getRandomNumber, getArrayRandomItems } from "@/utils"
export function useTopicCreate(){
	
	const state = reactive({
		params: {},
		list: [],
		result: [],
		title: [],
		ids: []
	})
	
	const useTopicCreateList = async (params = {}) => {
		state.params = params;
		state.list = [];
		state.result = [];
		state.title = [];
		state.ids = [];
		const id = params.data_source_id ? params.data_source_id * 1 : params.category_id * 1 
		// data
		let data = null
		// 查数据
		let resData = null
		if(params.isRand) {
			if(['XJZZC', 'XJZXPY'].includes(state.params.type)) {
				data = params.list.map(item => `${item.word}-${item.word_similar}`)
			}else if(['FYCJYC'].includes(state.params.type)){ // 反义词、近义词
				if(id == 17) {
					data = params.list.map(item => `${item.word}|${item.word_opposite}`)
				}
				if(id == 18) {
					data = params.list.map(item => `${item.word}|${item.word_synonym}`)
				}
			}else{
				data = params.list.map(item => item.word)
			}
		}else{
			resData = await createTopic(params)
			data = resData.content
		}
		// 词组
		// if(params.type === 'CiGroup') {
		// 	return Promise.resolve(data);
		// }
		if([12].includes(id)) {
			await ZC(data)
		}
		if(id === 13) {
			if(params.type === 'BQDY') { await BQDY(data) }
			if(['CiGroup', 'KPYXCY'].includes(params.type)) { await KPYXCY(data) }
		}
		if(id === 16) { await XZQDY(data) }
		if([17, 18].includes(id)) { await FYCJYC(data) }
		if([84].includes(id)) { await XJZZC(data) }
		if([66].includes(id)) {
			if(['PYXCY', 'KPYXCY'].includes(params.type)) { await KPYXCY(data) }
			// 补全成语
			if(params.type === 'BQCY') { await BQCY(data) }
		}
		// 保存题目
		if(params.autoSave) {
			return useSaveTopicList(params)
		}else{
			console.log('state.list', state.list)
			return state.list;
		}
	}
	
	/**
	 * 创建题目并定入
	 */
	const useSaveTopicList = (params) => {
		
		return new Promise((resolve, rejetc) => {
			if(params.isRand) {
				savePrintData(params).then((res) => {
					resolve(res)
				}).catch(() => {
					rejetc()
				})
				return
			}
			const req = {
				"content": JSON.stringify(state.list),
				"result": JSON.stringify(state.result),
				"category_id": params.category_id,
				"grade_id": params.grade_id,
				"sub_category_id": params.sub_category_id,
				"images": params.images,
				"type": params.topicType || undefined,
				"title_topic": formatTitle(),
			}
			// if(params.isRand) {
			// 	req.content = state.ids.join((','))
			// 	req.result = ''
			// }
			saveTopic(req).then((res) => {
				resolve(res)
				// const data = res.content
				// uni.navigateTo({
				// 	url: `/pagesTopic/topicAnswer/index?id=${data.id}`
				// })
			}).catch(() => {
				rejetc()
			})
		})
	}
	/**
	 * 创建打印数据
	 */
	const savePrintData = (params) => {
		const req = {
			"content": state.ids.join(','),
			"result": '',
			"category_id": params.category_id,
			"grade_id": params.grade_id,
			"sub_category_id": params.sub_category_id,
			"images": params.images,
		}
		return new Promise((resolve, reject) => {
			createPrint(req).then(res => {
				resolve(res)
			}).catch(() => {
				reject()
			})
		})
	}
	/**
	 * 处理标题
	 */
	const formatTitle = () => {
		const joinTitle = state.title.join(', ');
		return joinTitle.substring(0, 30)
	}
	/**
	 * 组词
	 */
	const ZC = (data) => {
		return new Promise((resolve, reject) => {
			getBasis({type: 1}).then(res => {
				// 组词
				const groupWords = res.content[0].words
				// 分割词组
				const wordsArray = groupWords.split(' ')
				data.forEach(word => {
					const zc = wordsArray.filter(w => w.includes(word) && w.length < 3)
					const zcCount = getArrayRandomItems(JSON.parse((JSON.stringify(zc))), 5)
					const hasZc = zcCount.every(item => item === undefined)
					if(!hasZc) {
						state.list.push(word)
						state.result.push(zcCount.filter(item => !!item))
						state.title.push(word)
					}
				})
				resolve()
			})
		})
	}
	
	/**
	 * 看拼音，写词语。看拼音，写成语
	 */
	const KPYXCY = (data) => {
		return new Promise((resolve, reject) => {
			data.forEach(item => {
				// 看拼音，写成语
				if(state.params.type === 'PYXCY' && item.length === 4) {
					// 获取拼音
					const py = pinyin(item, { type: 'array' })
					state.list.push(py)
					state.title.push(py.join(' '))
					state.result.push(item)
				}
				// 看拼音，写词组
				if(state.params.type === 'KPYXCY' && item.length === 2) {
					// 获取拼音
					const py = pinyin(item, { type: 'array' })
					state.list.push(py)
					state.title.push(py.join(' '))
					state.result.push(item)
				}
			})
			resolve()
		})
	}
	
	/**
	 * 选正确读音
	 */
	const XZQDY = (data) =>  {
		return new Promise((resolve, reject) => {
			getBasis({type: 1}).then(res => {
				// 组词
				const groupWords = res.content[0].words
				// 分割词组
				const wordsArray = groupWords.split(' ')
				data.forEach(item => {
					// 可分割
					const canSplit = item.indexOf('|') !== -1
					
					let split = null
					let result = null
					let index = null
					let pinyi = null
					let group = null
					if(canSplit) {
						split = item.split('|')
						result = wordsArray.filter(word => word.includes(split[0]) && word.length < 3)
						index = getRandomNumber(0, result.length - 1)
						pinyi = split[1].split('-')
						group = result[index]
					}else{
						
					}
					console.log(1111)
					console.log(result)
					console.log(index)
					console.log(pinyi)
					console.log(group)
				
					state.list.push({
						index: result[index].indexOf(split[0]),
						group,
						pinyi
					})
					
					const wordsPinyi = pinyin(group, { type: 'array' })
					const indexPinyi = pinyi.findIndex(obj1 => wordsPinyi.find(obj2 => obj2 === obj1))
					state.result.push({ index: indexPinyi, pinyi: pinyi[indexPinyi]})
					state.title.push(split[0])
				})
				resolve()
			})
		})
	}
	
	/**
	 * 反义词、近义词
	 */
	const FYCJYC = (data) => {
		return new Promise((resolve, reject) => {
			data.forEach(item => {
				const split = item.split('|')
				state.list.push(split[0])
				state.result.push(split[1])
				state.title.push(split[0])
			})
			resolve()
		})
	}
	
	/**
	 * 补全读音
	 */
	const BQDY = (data) =>  {
		return new Promise((resolve, reject) => {
			data.forEach(item => {
				const index = getRandomNumber(0, item.length - 1)
				const words = item[index]
				const pinyi = pinyin(words)
				if(item.length === 2) {
					state.list.push({
						word: item,
						index,
						pinyi: pinyi.slice(0, 1)
					})
					state.result.push(pinyi)
					state.title.push(item)
				}
			})
			resolve()
		})
	}
	
	/**
	 * 形近字组词
	 */
	const XJZZC = (data) =>  {
		console.log('data', data)
		return new Promise((resolve, reject) => {
			data.forEach(item => {
				let split = null
				let word = null
				const group = []
				const results = []
				if(state.params.isRand) {
					word = item.split('-')
				}else{
					split = item.split('|')
					word = split[0].split('-')
				}
				word.forEach((item, index) => {
					const w = word[index]
					// 形近字组词
					if(state.params.type === 'XJZZC') {
						group.push({
							word: w,
							pinyi: pinyin(w),
						})
						if(!state.params.isRand){
							results.push([split[1], split[2]].filter(word => word.indexOf(w) !== -1)[0])
						}
					}
					// 形近字写拼音
					if(state.params.type === 'XJZXPY') {
						group.push({word: w})
						results.push(pinyin(w))
					}
				})
				state.list.push(group)
				state.result.push(results)
				if(!state.params.isRand){
					state.title.push(`${split[1]} ${split[2]}`)
				}
			})
			resolve()
		})
	}
	/**
	 * 补全成语
	 */
	const BQCY = (data) => {
		return new Promise((resolve, reject) => {
			data = data.filter(item => item.length === 4)
			data.forEach(item => {
				let index1 = getRandomNumber(0, 3)
				let index2 = getRandomNumber(0, 3)
				if((index2 === index1)) {
					if(index2 === item.length -1) {
						index2--
					}else{
						index2++
					}
				}
				const word = item.split('')
				word[index1] = ''
				word[index2] = ''
				state.list.push({
					word,
					pinyi: pinyin(item, { type: 'array' }),
					space: [index1, index2]
				})
				state.result.push(item)
				state.title.push(word)
			})
			resolve()
		})
	}
	
	/**
	 * 格式化生成的数据
	 */
	const useFormatCreateData = (data, type) => {
		const newData = {}
		if(['IMAGE'].includes(type)) {
			newData.data = data
			newData.result = ''
		}
		// KPYXCY：看拼音，写词语。PYXCY；写成语。XJZZC：形近字组词。XJZXPY：形近字写拼音。BQCY：补充词语。ZC：组词。BQDY：补全读单
		if(['KTSH'].includes(type)) {
			return data
		}
		// KPYXCY：看拼音，写词语。PYXCY；写成语。XJZZC：形近字组词。XJZXPY：形近字写拼音。BQCY：补充词语。ZC：组词。BQDY：补全读单
		if(['KPYXCY', 'PYXCY', 'XJZZC', 'XJZXPY', 'BQCY', 'ZC', 'BQDY', 'XZQDY', 'FYCJYC', 'LYL'].includes(type)) {
			const content = JSON.parse(data.content)
			const result = data.result ? JSON.parse(data.result) : {}
			newData.data = content
			newData.result = result
		}
		return newData
	}
	
	return {
		stateTopic: state,
		useTopicCreateList,
		useSaveTopicList,
		useFormatCreateData
	}
	
	
}